﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PersonaLibrary.Data;
using PersonaLibrary.Data.ServiceReference;

namespace PersonaLibrary.ViewModel
{
	internal class ReferenceEditableItem<TEntity> : EditableItemViewModel<TEntity>
		where TEntity : IDBEntity
	{
		protected DataServiceContextWrapper Context = new DataServiceContextWrapper();
		
		protected TEntity GetItemById(int id)
		{
			return Context.CreateAndExecuteQuery<TEntity>(string.Format("{0}?$filter=Id eq {1}", typeof(TEntity).Name, id)).Single();
		}

		public virtual bool NotSaved 
		{
			get { return EditableItem.Id == 0; }
		}

		public Visibility NotSavedView
		{
			get
			{
				if (NotSaved)
					return Visibility.Visible;

				return Visibility.Hidden;
			}
		}

		public override string Name
		{
			get
			{
				return EditableItem.ToString();
			}
		}

		public override void Commit()
		{
			if (EditableItem.Id == 0)
				Context.AddObject(typeof(TEntity).Name, EditableItem);
			else
				Context.UpdateObject(EditableItem);
			Context.SaveChanges();
			base.Commit();
		}

		public override void Delete()
		{
			Context.DeleteObject(EditableItem);
			Context.SaveChanges();
			base.Delete();
		}

		public override void Dispose()
		{
		}

		public override string ToString()
		{
			return EditableItem.ToString();
		}
	}
}
